package com.example.myproject.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.myproject.model.Comment;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper
@Repository
public interface CommentMapper extends BaseMapper<Comment> {
    
    @Select("SELECT * FROM comment WHERE torrent_id = #{torrentId} AND parent_id IS NULL ORDER BY " +
            "CASE WHEN #{sort} = 'top' THEN likes_count ELSE NULL END DESC, " +
            "CASE WHEN #{sort} = 'newest' OR #{sort} IS NULL THEN create_time END DESC " +
            "LIMIT #{offset}, #{limit}")
    List<Comment> findByTorrentId(@Param("torrentId") Integer torrentId, 
                                 @Param("sort") String sort,
                                 @Param("offset") Integer offset,
                                 @Param("limit") Integer limit);

    @Select("SELECT * FROM comment WHERE parent_id = #{parentId} ORDER BY create_time ASC")
    List<Comment> findRepliesByParentId(@Param("parentId") Integer parentId);

    @Select("SELECT COUNT(*) FROM comment WHERE torrent_id = #{torrentId} AND parent_id IS NULL")
    Integer countByTorrentId(@Param("torrentId") Integer torrentId);

    @Update("UPDATE comment SET is_deleted = 1 WHERE comment_id = #{commentId}")
    void markDeleted(Long commentId);

    @Update("UPDATE comment SET is_deleted = 1 WHERE parent_id = #{parentId}")
    void markChildrenDeleted(Long parentId);

    @Select("SELECT * FROM comment WHERE parent_id = #{parentId} AND is_deleted = 0")
    List<Comment> findActiveChildren(Long parentId);

    @Select("SELECT * FROM comment WHERE comment_id = #{commentId}")
    Comment selectByCommentId(Long commentId);

    @Select("SELECT * FROM comment WHERE torrent_id = #{torrentId} AND parent_id IS NULL AND is_deleted = 0 ORDER BY create_time DESC LIMIT #{offset}, #{limit}")
    List<Comment> findByTorrentIdAndNotDeleted(@Param("torrentId") Integer torrentId, @Param("sort") String sort, @Param("offset") int offset, @Param("limit") int limit);

    @Select("SELECT COUNT(*) FROM comment WHERE torrent_id = #{torrentId} AND parent_id IS NULL AND is_deleted = 0")
    Integer countByTorrentIdAndNotDeleted(@Param("torrentId") Integer torrentId);
}
